package com.fooddelivery;

import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class OrderFrame extends JFrame {
    private JComboBox<String> restaurantComboBox;
    private JComboBox<String> menuItemComboBox;
    private JSpinner quantitySpinner;
    private JTextArea orderSummaryArea;

    public OrderFrame(int userId) {
        setTitle("Place Order");
        setSize(500, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(3, 2));

        inputPanel.add(new JLabel("Restaurant:"));
        restaurantComboBox = new JComboBox<>();
        loadRestaurants();
        inputPanel.add(restaurantComboBox);

        inputPanel.add(new JLabel("Menu Item:"));
        menuItemComboBox = new JComboBox<>();
        inputPanel.add(menuItemComboBox);

        inputPanel.add(new JLabel("Quantity:"));
        quantitySpinner = new JSpinner(new SpinnerNumberModel(1, 1, 10, 1));
        inputPanel.add(quantitySpinner);

        panel.add(inputPanel, BorderLayout.NORTH);

        orderSummaryArea = new JTextArea();
        orderSummaryArea.setEditable(false);
        panel.add(new JScrollPane(orderSummaryArea), BorderLayout.CENTER);

        JButton placeOrderButton = new JButton("Place Order");
        placeOrderButton.addActionListener(e -> placeOrder(userId));
        panel.add(placeOrderButton, BorderLayout.SOUTH);

        add(panel);
    }

    private void loadRestaurants() {
        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT * FROM restaurants";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                restaurantComboBox.addItem(rs.getString("name"));
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private void placeOrder(int userId) {
        String restaurantName = (String) restaurantComboBox.getSelectedItem();
        String menuItemName = (String) menuItemComboBox.getSelectedItem();
        int quantity = (int) quantitySpinner.getValue();

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "INSERT INTO orders (user_id, restaurant_id, total_price) VALUES (?, ?, ?)";
            PreparedStatement stmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, userId);
            stmt.setInt(2, getRestaurantId(restaurantName));
            stmt.setDouble(3, getMenuItemPrice(menuItemName) * quantity);
            stmt.executeUpdate();

            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                int orderId = rs.getInt(1);
                String itemSql = "INSERT INTO order_items (order_id, menu_item_id, quantity) VALUES (?, ?, ?)";
                PreparedStatement itemStmt = conn.prepareStatement(itemSql);
                itemStmt.setInt(1, orderId);
                itemStmt.setInt(2, getMenuItemId(menuItemName));
                itemStmt.setInt(3, quantity);
                itemStmt.executeUpdate();
            }

            JOptionPane.showMessageDialog(this, "Order placed successfully!");
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private int getRestaurantId(String name) throws SQLException {
        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT id FROM restaurants WHERE name = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt("id");
            }
        }
        return -1;
    }

    private int getMenuItemId(String name) throws SQLException {
        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT id FROM menu_items WHERE name = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt("id");
            }
        }
        return -1;
    }

    private double getMenuItemPrice(String name) throws SQLException {
        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT price FROM menu_items WHERE name = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getDouble("price");
            }
        }
        return 0.0;
    }
}
